package cn.jasonone.jfx.factory;

import cn.jasonone.jfx.context.BaseController;
import cn.jasonone.jfx.manager.JfxStageManager;
import cn.jasonone.jfx.util.NodeUtil;
import javafx.application.Platform;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author xujie
 * @version 1.0
 * @date 2021/12/22 12:25
 */
@Component("stageFactory")
public class DefaultStageFactory implements StageFactory {
    private Map<String, Stage> stageMap = new HashMap<>();
    @Resource
    private SceneFactory sceneFactory;
@Resource
    private NodeUtil nodeUtil;
    @Override
    public Stage getStage(String id, String title) {
        if (!stageMap.containsKey(id)) {
            Stage stage = new Stage();
            stageMap.put(id, stage);
            stage.addEventHandler(WindowEvent.WINDOW_CLOSE_REQUEST, new EventHandler<WindowEvent>() {
                @Override
                public void handle(WindowEvent windowEvent) {
                    if(JfxStageManager.PRIMARY_STAGE_KEY.equals(id)){
                        return ;
                    }
                    Stage stage = stageMap.remove(id);
                    Scene scene = stage.getScene();
                    sceneFactory.destroy(scene);
                    Set<BaseController> controllers = nodeUtil.getControllers(scene);
                    for (BaseController controller : controllers) {
                        // 移除舞台
                        controller.removeStage(stage);
                        // 移除场景
                        controller.removeScene(scene);
                    }
                }
            });
        }
        Stage stage = stageMap.get(id);
        stage.setTitle(title);
        return stage;
    }
}
